package com.maiji.cloud.cfgbeans;

import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.utils.Unlogin;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RestTemplate restTemplate;

	 private static final String REST_URL_APPLOGIN = "http://MAIJICLOUD-APPLOGIN";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        if(request.getMethod().equals("OPTIONS")) return false;

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 如果注解不为null, 说明不需要登录, 直接放过
        Unlogin unlogin = method.getAnnotation(Unlogin.class);
        if (unlogin != null) return true;

        String maijiToken = request.getHeader("maijiToken");
        if (StringUtil.isBlank(maijiToken)) {
            request.getRequestDispatcher("/common/tokenInvalid").forward(request, response);
            return true;
        }
        BaseResDto resultDto = restTemplate.getForObject(REST_URL_APPLOGIN + "/common/checkToken/{maijiToken}", BaseResDto.class, maijiToken);
        if (resultDto.getStatus() == Status.SUCCESS) return true;
        else request.getRequestDispatcher("/common/tokenInvalid").forward(request, response);
        return false;
	}

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
